package com.zyy.service.config.db;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 *@author zhangyangyang
 *@createTime 2023417 17:14
 *@description 数据库连接配置
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "labelEntityManager", transactionManagerRef = "labelTransactionManager", basePackages = {
    "com.zyy.service.repo"} //设置dao（repo）所在位置
)
public class LabelDataSourceConfig {

    @Bean(name = "labelDataSource") @ConfigurationProperties("spring.datasource.label")
    public DataSource labelDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "labelEntityManager")
    public LocalContainerEntityManagerFactoryBean labelEntityManagerFactory(
        EntityManagerFactoryBuilder builder,
        @Qualifier("labelDataSource") DataSource dataSource) {
        return builder.dataSource(dataSource)
            //设置实体类所在位置
            .packages("com.zyy.service.entity").persistenceUnit("labelPersistenceUnit").build();
    }

    @Bean(name = "labelTransactionManager") PlatformTransactionManager labelTransactionManager(
        @Qualifier("labelEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}
